#pragma once

#include<iostream>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<string.h>
#include<functional>
#include<string>
#include<pthread.h>
#include<time.h>

#include"Log.hpp"


class Client
{
public:
    Client(int ip,int port)
    :_is_running(false)
    {
        bzero(&_server_addr,sizeof(_server_addr));
        _server_addr.sin_addr.s_addr=ip;
        _server_addr.sin_family=AF_INET;
        _server_addr.sin_port=port;

        _sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(0>_sockfd)
        {
            Log(FATAL,"create sockfd error\n");
            exit(-1);
        }
        Log(DEBUG,"create sockfd successfully\n");
    }

    void Start()
    {
        _is_running=true;
        if(0>connect(_sockfd,(struct sockaddr*)&_server_addr,sizeof(_server_addr)))
        {
            Log(FATAL,"connect fail\n");
            exit(-1);
        }
        while(_is_running)
        {
            //向服务端发送请求报文
            char request_buf[1024];
            strcpy(request_buf,"hello ,i am client\n");
            int wn=write(_sockfd,request_buf,sizeof(request_buf));
            if(wn<0)
            {
                Log(ERROR,"write fail\n");
                continue;
            }
            Log(DEBUG,"write: %s\n",request_buf);
            sleep(2);
        }
    }

    ~Client()
    {
        if(0<_sockfd)
        {
            close(_sockfd);
        }
    }

private:
    int _sockfd;
    struct sockaddr_in _server_addr;
    bool _is_running;
};